package ks.client.gui.plugin.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JList;
import org.w3c.dom.Document;
import ks.client.UserContext;
import ks.client.controllers.commands.PluginListCommandController;
import ks.client.ipc.Client;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.managers.plugin.Plugin;
import ks.managers.plugin.PluginManager;


/**
 * 
 * If a plugin is selected, then when the "Selected Plugin Information"
 * button is pressed, a plugin-info command is sent to the server.
 * 
 * @author Jennifer Hunt
 *
 */
public class PluginInformationClickController implements ActionListener{
	
	Lobby lobby;
	JList plugins;
	UserContext context;
	
	/**
	 * Constructor for PluginInformationClickController.
	 * 
	 * @param lobby
	 */
	public PluginInformationClickController(Lobby lobby, JList plugins) {
		this.lobby = lobby;
		this.plugins = plugins;
		context = lobby.getUserContext();
	}
	
	/**
	 * 
	 * When the button is clicked, the message is created and sent. 
	 * 
	 */
	public void actionPerformed(ActionEvent evt){
		try{
			context.getUser().isEmpty();
			}catch(NullPointerException npe){
				System.out.println("This option is only available to logged in users.");
				return;
			}
		try{
		String name = plugins.getSelectedValue().toString();
		if(!name.isEmpty()){
			String s = "<command version= \"1.0\" id=\"589a39591271844e3fbe32bbb9281ad9\">" +
			"<plugin-info plugin =\"" + name + "\"/>" + 
			"</command>";
			
			Document d = Message.construct(s);
			Message m = new Message(d);

			//send to server
			UserContext uc = lobby.getUserContext();
			Client c = uc.getClient();
			c.sendToServer(m);
		}
		
		UserContext context = lobby.getUserContext();
		PluginManager pm = context.getPluginManager();
		Plugin p = pm.getPlugin(name);
		lobby.getPMGUI().getVar().setText(p.getName());
		lobby.getPMGUI().getStat().setText("" + p.getSuspended());
		lobby.getPMGUI().getUpd().setText(p.getDate());
		lobby.getPMGUI().getWin().setText("" + p.getWins());
		lobby.getPMGUI().getLos().setText("" + p.getLosses());
			
		new PluginListCommandController(lobby).send();
	}catch(NullPointerException e){
		System.out.println("Please select a plugin.");
	}
	}

}
